<?php
/**
 * Joomla! 1.5 component ArticleCashRewards
 *
 * @version $Id: mypage.php 2009-05-10 01:47:01 svn $
 * @author Maverick
 * @package Joomla
 * @subpackage components.models
 * @link http://joomladev.boddunan.com
 * @license GNU/GPL
 *
 * Review and approve the articles and assign points and cash rewards.
 * Users can see their articles and the points/cash rewards assigned in the front-end module.
 */

// no direct access
defined('_JEXEC') or die('Restricted access');

jimport('joomla.application.component.model');
require_once(JPATH_SITE.DS.'components'.DS.'com_content'.DS.'helpers'.DS.'route.php');
/**
 * ArticleCashRewards Component ArticleCashRewards Model
 *
 * @author      notwebdesign
 * @package		Joomla
 * @subpackage	ArticleCashRewards
 * @since 1.5
 */
class ArticleCashRewardsModelMyPage extends JModel {
	var $_total = null;
	var $_pagination = null;
    var $_error = null;
    
	function __construct(){
	  parent::__construct();

      global $mainframe, $option;
      $config = JFactory::getConfig();
      // Get the pagination request variables
      $this->setState('limit', $mainframe->getUserStateFromRequest($option.'.limit', 'limit', $config->getValue('config.list_limit'), 'int'));
      $this->setState('limitstart', JRequest::getVar('limitstart', 0, '', 'int'));

      // In case limit has been changed, adjust limitstart accordingly
      $this->setState('limitstart', ($this->getState('limit') != 0 ? (floor($this->getState('limitstart') / $this->getState('limit')) * $this->getState('limit')) : 0));
	}

	function getDashboard(){

	  	global $mainframe, $option, $acr_config;
	    // Get a database object
		$db =& JFactory::getDBO();
		$user =& JFactory::getUser();
        $ruser = JRequest::getVar('uid', null, '', 'INTEGER');
        $params = JComponentHelper::getParams('com_articlecashrewards');
        $dashboard = null;
        
        $userid = null;
        
        if(isset($ruser)){
            $userid = $ruser;
        }else{
            if ( !$user->id ) {
                $msg = JText::_('Not authorised' );
                $mainframe->redirect('index.php', $msg);
            } else {
                $userid = $user->id;
            }
        }

        // Total Articles
		$query = 'SELECT COUNT(*) as tot_articles FROM '. TABLE_ACR_CONTENT  .
            ' acr LEFT JOIN #__content c ON acr.article_id=c.id WHERE c.created_by='.
            $userid. ' AND acr.status=' . STATUS_APPROVED;
        $db->setQuery($query);
		$result = $db->loadAssoc();
        $dashboard->article_count = ($result['tot_articles'] == '')?'0':$result['tot_articles'];
        
		$query = 'SELECT cash, points FROM '. TABLE_ACR_USERS  . ' WHERE id='. $userid;
        $db->setQuery($query);
		$result_users = $db->loadAssoc();
        $dashboard->article_cash = ($result_users['cash'] == '')?'0':$result_users['cash'];

        if(!strcasecmp($acr_config[CONFIG_POINTS_SYSTEM],POINTS_SYSTEM_AUP) == 1){
            $dashboard->total_points = ($result_users['points'] == '')?'0':$result_users['points'];
        }
        
        //Misc user submissions payments
        if($acr_config[CONFIG_ENABLE_WEBLINKS] == '1'){
            $query = 'SELECT count(*) as tot_weblinks, sum(cash_rewards) as weblinks_amount FROM ' . TABLE_ACR_WEBLINKS .
                ' WHERE userid=' . $userid . ' AND status=' . STATUS_APPROVED;
            $db->setQuery($query);
            $result = $db->loadAssoc();
            $dashboard->weblinks_amount = ($result['weblinks_amount'] == '')?'0.00':$result['weblinks_amount'];
            $dashboard->weblinks_count = ($result['tot_weblinks'] == '')?'0':$result['tot_weblinks'];
        }

        if($acr_config[CONFIG_ENABLE_REFERRALS] == '1'){
            $query = "SELECT a.referrees FROM #__alpha_userpoints AS a"
                    ." WHERE a.userid=" . $userid;
            $db->setQuery($query);
            $dashboard->referral_count = $db->loadResult();

            if($dashboard->referral_count > 0){
                $query = 'SELECT SUM(amount) FROM ' . TABLE_ACR_REFERRALS .
                    ' WHERE referredby=' . $userid . ' AND status=' . STATUS_APPROVED;
                $db->setQuery($query);
                $dashboard->referral_amount = $db->loadResult();
            }else{
                $dashboard->referral_amount = '0.00';
            }
        }

        // Awards
        if($acr_config[CONFIG_ENABLE_AWARDS] == '1'){
            $query = 'SELECT aa.amount, aa.description as description, at.description as award,' .
                    ' aa.pay_date as award_date FROM ' . TABLE_ACR_ADHOC . ' AS aa ' .
                    ' LEFT JOIN ' . TABLE_ACR_ADHOC_TYPES . ' at ON aa.type=at.id' .
                    ' WHERE aa.author=' . $userid;
            $db->setQuery($query);
            $dashboard->awards = $db->loadObjectList();
        }

        // User information
        if(strcasecmp($acr_config[CONFIG_POINTS_SYSTEM],POINTS_SYSTEM_AUP) == 1){

            $referrerid = $this->_checkUser();

            $userinfo                   = AlphaUserPointsHelper::getUserInfo ( $referrerid );
            $dashboard->name            = $userinfo->name;
            $dashboard->username        = $userinfo->username;
            $dashboard->birthdate       = $userinfo->birthdate;
            $dashboard->total_points    = $userinfo->points;
            $referraluser               = $userinfo->referraluser;
            
            $referralname = "";
            if ( $referraluser ) {
                $referralinfo = AlphaUserPointsHelper::getUserInfo ( $referraluser );
                $dashboard->refusername = $referralinfo->username;
                $dashboard->refname = $referralinfo->name;
            }

            $userrankinfo = AlphaUserPointsHelper::getUserRank ( $referrerid );
    		$medalslistuser = AlphaUserPointsHelper::getUserMedals ( $referrerid );
        }else{
            $query = 'SELECT name, username FROM #__users WHERE=id' . $userid;
            $db->setQuery($query);
            $result = $db->loadObjectList();
            $dashboard->name = $result->name;
            $dashboard->username = $result->username;
        }

        // Totals
		$query = 'SELECT points, cash, redeamed, paid FROM ' . TABLE_ACR_USERS . ' WHERE id=' . $userid;
		$db->setQuery($query);
		$result = $db->loadAssoc();
        $dashboard->total_cash = ($result['cash'] == '')?'0.00':$result['cash'];
        $dashboard->total_paid = ($result['paid'] == '')?'0.00':$result['paid'];

		return $dashboard;
	}
    
	function _checkUser()  {
		global $mainframe;

		// active user
		$user = & JFactory::getUser();

		// check referre ID
		$referrerid = @$_SESSION['referrerid'];

		if ( !$user->id || !$referrerid ) {
			$msg = JText::_('Not authorized.' );
			$mainframe->redirect('index.php', $msg);
		} else return $referrerid;

	}
	function getAuPoints($params) {
		global $mainframe;

		$db			      =& JFactory::getDBO();

		$nullDate	= $db->getNullDate();
		$date =& JFactory::getDate();
		$now  = $date->toMySQL();

		// exclude specific users of this list
		$excludeuser = array();
		$excludeusers = "";
		$query = "SELECT exclude_items FROM #__alpha_userpoints_rules WHERE `plugin_function`='sysplgaup_excludeusers' AND `published`='1'";
		$db->setQuery( $query );
		$result  = $db->loadResult();
		if ( $result ) {
			$excludeuser = explode( ",", $result);
			for ($i=0, $n=count($excludeuser); $i < $n; $i++) {
				$excludeusers .= "\nAND aup.referreid!='" . trim($excludeuser[$i]) . "'";
			}
		}

		$activity   = $params->get('activity', 0);

		$typeActivity = "";

		if ( $activity == 1 )
		{
			$typeActivity = " AND a.points >= 1";
		}
		elseif ( $activity == 2 )
		{
			$typeActivity = " AND a.points < 0";
		}


		// Get the pagination request variables
		$limit = $mainframe->getUserStateFromRequest('com_alphauserpoints.limit', 'limit', $mainframe->getCfg('list_limit'), 'int');
		$limitstart = JRequest::getVar('limitstart', 0, '', 'int');
		// In case limit has been changed, adjust limitstart accordingly
		$limitstart = ( $limit != 0 ? (floor( $limitstart / $limit ) * $limit) : 0);
		$query = "SELECT a.insert_date, a.referreid, a.points AS last_points, a.datareference, u.".$params->get('usrname', 'name')." AS usrname, r.rule_name, r.plugin_function"
			   . " FROM #__alpha_userpoints_details AS a, #__alpha_userpoints AS aup, #__users AS u, #__alpha_userpoints_rules AS r"
			   . " WHERE aup.referreid=a.referreid AND aup.userid=u.id AND a.approved='1' AND (a.expire_date>='".$now."' OR a.expire_date='0000-00-00 00:00:00') AND r.id=a.rule"
			   . $excludeusers
			   . $typeActivity
			   . " ORDER BY a.insert_date DESC"
		 	   ;
		$total = @$this->_getListCount($query);
		$result = $this->_getList($query, $limitstart, $limit);
		return array($result, $total, $limit, $limitstart);

	}

	function getUserArticles(){

	  	global $mainframe, $option;;
	    // Get a database object
		$db =& JFactory::getDBO();
		$user =& JFactory::getUser();
		$filter_order		= $mainframe->getUserStateFromRequest( "$option.filter_order",		'filter_order',		'a.id',	'cmd' );
		$filter_order_Dir	= $mainframe->getUserStateFromRequest( "$option.filter_order_Dir",	'filter_order_Dir',	'',		'word' );

		$orderby 	= ' ORDER BY '. $filter_order .' '. $filter_order_Dir;

		$query = 'SELECT a.id, a.alias, a.title, a.sectionid, a.catid, s.title AS section, cc.title AS category,'.
			' acr.points, acr.cash, acr.remarks, acr.status, '.
			' s.access AS sec_access, cc.access AS cat_access, s.published AS sec_state, cc.published AS cat_state,'.
			' CASE WHEN CHAR_LENGTH(a.alias) THEN CONCAT_WS(":", a.id, a.alias) ELSE a.id END as slug,'.
			' CASE WHEN CHAR_LENGTH(cc.title) THEN CONCAT_WS(":", cc.id, cc.title) ELSE cc.id END as catslug'.
			' FROM #__content AS a' .
			' LEFT JOIN #__categories AS cc ON cc.id = a.catid' .
			' LEFT JOIN #__sections AS s ON s.id = a.sectionid' .
			' LEFT JOIN #__users AS u ON u.id = a.created_by' .
			' LEFT JOIN ' . TABLE_ACR_CONTENT  . ' AS acr ON acr.article_id = a.id' .
			' WHERE a.created_by = '.$user->id.' AND (a.state=1 OR a.state=0)'.$orderby;

		$db->setQuery($query, $this->getState('limitstart'), $this->getState('limit'));
		$rows = $db->loadObjectList();
//echo $query;
//		$query = 'SELECT SUM(acr.points) AS tot_points, SUM(acr.cash) AS tot_cash FROM '.
//			TABLE_ACR_CONTENT  . ' acr, #__content c WHERE c.created_by='.$user->id.' AND '.
//			' acr.article_id=c.id';
//
//		$db->setQuery($query);
//		$temp = $db->loadObjectList();
//
//		foreach ( $temp as $row ){
//			$lists['tot_points']	= $row->tot_points;
//			$lists['tot_cash']		= $row->tot_cash;
//		}

		$lists['order_Dir']	= $filter_order_Dir;
		$lists['order']		= $filter_order;

		$result->rows = $rows;
		$result->lists = $lists;

        $query = 'SELECT count(*) FROM ' . TABLE_ACR_CONTENT . 'ac LEFT JOIN #__content c'.
            ' ON ac.article_id = c.id AND c.created_by=' . $user->id;
        $db->setQuery($query);
        $this->_total = $db->loadResult();

		return $result;
	}

    function getUserReferrals(){

	  	global $mainframe, $option;;
	    // Get a database object
		$db =& JFactory::getDBO();
		$user =& JFactory::getUser();

		$query = 'SELECT ar.id, u.username AS referral, ar.amount as earnings, arr.articles,'.
            ' arr.description as level, ar.status as status FROM ' . TABLE_ACR_REFERRALS .
            ' ar LEFT JOIN ' . TABLE_ACR_REFEREE_RULES . ' arr ON ar.level = arr.id LEFT JOIN' .
            ' #__users u ON ar.userid=u.id WHERE ar.referredby=' .
            $user->id . ' ORDER BY ar.status DESC';
		$db->setQuery($query, $this->getState('limitstart'), $this->getState('limit'));
		$result = $db->loadObjectList();
//echo $query;

        $query = 'SELECT count(*) FROM ' . TABLE_ACR_REFERRALS . ' WHERE referredby=' . $user->id;
        $db->setQuery($query);
        $this->_total = $db->loadResult();
        
		return $result;

    }
    
	function getWebLinks(){

	  	global $mainframe, $option;;
	    // Get a database object
		$db =& JFactory::getDBO();
		$user =& JFactory::getUser();

		$query = 'SELECT value, date_submitted, status, description, remarks FROM ' .
            TABLE_ACR_WEBLINKS . ' aw WHERE userid=' . $user->id . ' ORDER BY aw.date_submitted DESC';
		$db->setQuery($query, $this->getState('limitstart'), $this->getState('limit'));
		$rows = $db->loadObjectList();

		$result->rows = $rows;

        $query = 'SELECT count(*) FROM ' . TABLE_ACR_WEBLINKS . ' aw WHERE userid=' . $user->id;
        $db->setQuery($query);
        $this->_total = $db->loadResult();
        
		return $result;
	}

    function saveProfile(){

        global $mainframe, $acr_config;
        $user               =& JFactory::getUser();
        $db                 =& JFactory::getDBO();
        $payee_name         = JRequest::getString( 'payee_name', null);
        $payee_contact      = JRequest::getString( 'payee_contact', null);
        $payee_threshold    = JRequest::getVar( 'payee_threshold', '0.00', 'post', 'INTEGER');
        $payee_address1     = JRequest::getVar( 'payee_address1', '', 'post', 'STRING');
        $payee_address2     = JRequest::getVar( 'payee_address2', '', 'post', 'STRING');
        $payee_address3     = JRequest::getVar( 'payee_address3', '', 'post', 'STRING');
        $payee_id_val       = JRequest::getVar( 'payee_identification', null, 'post', 'STRING');

        if($payee_threshold < $acr_config[CONFIG_MIN_PAYMENT_THRESHOLD]){
            $payee_threshold = 0+$acr_config[CONFIG_MIN_PAYMENT_THRESHOLD];
        }
//echo $acr_config[CONFIG_MIN_PAYMENT_THRESHOLD];
        $address = $payee_address1 . "^" . $payee_address2 . "^" . $payee_address3;

        $query = 'INSERT INTO ' . TABLE_ACR_USERS . '(id, contact_number, '.
            'cash_threshold, mailing_address) VALUES('. $user->id . ', ' .
            $db->quote($payee_contact) . ', ' . $db->quote($payee_threshold) . ',' . 
            $db->quote($address) . ') ON DUPLICATE KEY UPDATE contact_number=' . 
            $db->quote($payee_contact) . ', mailing_address=' . $db->quote($address) .
            ', cash_threshold=' . $payee_threshold;
        $db->setQuery($query);

        if(!$db->query()){
            return false;
        }

        if(isset($payee_name) && $payee_name != ''){
            $query =  'INSERT INTO ' . TABLE_ACR_USERS . '(id, payee_name) (SELECT id, "' . $payee_name .
                '" FROM ' . TABLE_ACR_USERS . ' WHERE id=' . $user->id . ' AND payee_name IS NULL)' .
                ' ON DUPLICATE KEY UPDATE payee_name="' . $payee_name . '"';
            $db->setQuery($query);
            if(!$db->query()){
                return false;
            }
        }
        if($payee_id_val){
            $query = 'SELECT security_code FROM ' . TABLE_ACR_USERS . ' WHERE id='.$user->id;
            $db->setQuery($query);
            $orig_code = $db->loadResult();

            if(null != $orig_code && strcmp($orig_code, $payee_id_val) == 0){
                $query = 'UPDATE ' . TABLE_ACR_USERS . ' SET security_code="1" WHERE id='.$user->id;
                $db->setQuery($query);
                $db->query();
            }else{
                $this->_error = JText::_('CODE_VALIDATED');
                return false;
            }
        }
        return true;
    }

    function saveWebLink(){

        $user =& JFactory::getUser();
        $db =& JFactory::getDBO();
        $weblink = JRequest::getVar( 'weblink_link', null);
        $description = JRequest::getString( 'weblink_desc', null);

        if($weblink == null || $user->id <= 0){
            return false;
        }
        
        $query =  'INSERT INTO ' . TABLE_ACR_WEBLINKS . '('.
            'value, userid, date_submitted, description) VALUES ("' .
            $weblink . '", ' . $user->id . ', now(), "' . $db->quote($description) . '")';
        $db->setQuery($query);
        if(!$db->query()){
            return false;
        }else{
            $query = 'INSERT INTO ' . TABLE_ACR_USERS . '(id, cash) VALUES(' .
                $user->id . ', 0) ON DUPLICATE KEY UPDATE cash=cash+0';
            $db->setQuery($query);
            if(!$db->query()){
                return false;
            }
        }

        return true;
    }

    function getMyProfile(){
        $user =& JFactory::getUser();
        $db =& JFactory::getDBO();

        $query = 'SELECT id, cash_threshold as payee_threshold, contact_number as payee_contact,' .
            ' payee_name, mailing_address, security_code FROM ' . TABLE_ACR_USERS . ' WHERE id=' . $user->id;

        $db->setQuery($query);
        $profile = $db->loadAssoc();

        $adds = explode("^", $profile['mailing_address']);
        if(count($adds) == 3){
            $profile['payee_address1'] = $adds['0'];
            $profile['payee_address2'] = $adds['1'];
            $profile['payee_address3'] = $adds['2'];
        }

        return $profile;
    }

	function getTotal(){
	    // Load the content if it doesn't already exist
	    if (empty($this->_total)) {

		    $user =& JFactory::getUser();
		    $db =& JFactory::getDBO();

	        $query = 'SELECT count(*) FROM #__content a WHERE a.created_by = '.$user->id.' AND (a.state=1 OR a.state=0)';
	        $db->setQuery( $query );

	        $this->_total = $db->loadResult();
	    }

	    return $this->_total;
	}
	function getPagination(){
	    // Load the content if it doesn't already exist
        jimport('joomla.html.pagination');
        $this->_pagination = new JPagination($this->getTotal(), $this->getState('limitstart'), $this->getState('limit') );
	    return $this->_pagination;
	}

    function getError(){
        return $this->_error;
    }
}
?>